package com.itcoon.cloud.framework.utils;

import org.springframework.lang.NonNull;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringFormatter {

    private static final String REGEX = "\\$\\{\\w+\\}";
    /*
     * commons-text
     * */
    public static String format(@NonNull String template, @NonNull Map<String, Object> paramMap){
        Matcher m = Pattern.compile(REGEX).matcher(template);
        StringBuffer sb = new StringBuffer();
        while(m.find()){
            String param = m.group();
            Object value = paramMap.get(param.substring(2, param.length() - 1));
            m.appendReplacement(sb,value == null ? "" : value.toString());
        }
        m.appendTail(sb);
        return sb.toString();
    }

}
